import {getUserTempId,getUserToken,saveUserToken,deleteUserToken} from '@/utils/userAuth'
import { Message } from 'element-ui'
import { reqLogin,reqUserInfo,reqLogout } from '@/api'
const actions ={
    //登录，
    async userLogin({commit},loginParams){
        const result = await reqLogin(loginParams)
        if (result.code ===200){
            //commit有用？有用 保存到vuex中 没有此步骤 跳转时首页无法获得个人信息
            commit('SAVE_USER_TOKEN',result.data.token)
            // Message.success('登录成功')
            saveUserToken(result.data.token)
            // return 'ok'
            // console.log('###');
            // return Promise.resolve('ok')
            
        }else{
            Message.error(result.message)
            return new Promise(()=>{})

        }
    },
    //获取用户个人信息
    async getUserInfo({commit}){
        const result =await reqUserInfo()
        if (result.code ===200){
            commit('SAVE_USER_INFO',result.data)
        }else{
            Message.error(result.message)
            return Promise.reject('fail')
        }

    },
    //退出登录
    async userLogout({commit}){
        const result =await reqLogout()
        if (result.code ===200){
            Message.success('退出登录')
            commit('LOGOUT')
            deleteUserToken()
        }else{
            Message.error(result.message)
            return new Promise(()=> {})
        }
    }

}
const mutations={
    SAVE_USER_TOKEN(state,token){
        state.userToken= token
    },
    SAVE_USER_INFO(state,info){
        state.userInfo= info
    },
    LOGOUT(state){
        state.userInfo={}
        state.userToken=''
    }
    
}

const state = {
   userTempId:getUserTempId(),
   userToken:getUserToken(),
   userInfo:{}
}

const getters = {}

export default {
    namespaced:true,
    actions,
    mutations,
    state,
    getters,
}